package com.itheima.controller;

import com.itheima.annotation.Log;
import com.itheima.po.InsertDept;
import com.itheima.po.UpdateDept;
import com.itheima.pojo.Dept;

import com.itheima.pojo.Result;
import com.itheima.service.DeptService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;

@RestController
@RequestMapping("/depts")
@CrossOrigin
public class DeptController {
    @Autowired
    private DeptService deptService;

//    @GetMapping("/depts")
//    public Result list2(){
//        //1. 加载文件 ,  获取原始数据
//        InputStream in = this.getClass().getClassLoader().getResourceAsStream("dept.txt");
//        List<String> lines = IOUtils.readLines(in, "UTF-8");
//
//        //2. 对原始数据进行处理 , 组装部门数据
//        List<Dept> deptList = lines.stream().map(line -> {
//            String[] parts = line.split(",");
//            Integer id = Integer.parseInt(parts[0]);
//            String name = parts[1];
//            LocalDateTime updateTime = LocalDateTime.parse(parts[2], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//            return new Dept(id, name, updateTime);
//        }).toList();
//
//        //2. 响应数据
//        return Result.success(deptList);
//    }

    /**
     * 查询所有部门
     */
    @GetMapping
    public Result selectAll() {
        List<Dept> depts = deptService.selectAll();
        return Result.success(depts);
    }

    /**
     * 删除部门
     */
    @Log
    @DeleteMapping
    public Result deleteById(Integer id) {
        boolean flag = deptService.deleteById(id);
        if (flag) {
            return Result.success("删除成功");
        }
        return Result.fail("删除失败");
    }

    /**
     * 增加部门
     */
    @PostMapping
    public Result insert(@RequestBody Dept dept) {
        return deptService.insert(dept);
    }

    /**
     * 查询回显
     */
    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id) {
        Dept dept = deptService.selectById(id);
        return Result.success(dept);
    }

    /**
     * 修改部门
     */
    @PutMapping
    public Result update(@RequestBody Dept dept) {

        return deptService.update(dept);
    }

    /**
     * 批量删除部门
     */
    @DeleteMapping("/deleteByIds")
    public Result deleteByIds(Integer[] ids) {
        System.out.println(ids);
        return deptService.deleteByIds(ids);
    }

    /**
     * 批量添加
     * @param depts
     * @return
     */
    @PostMapping("/insertBatch")
    public Result insert(@RequestBody List<Dept> depts) {
        System.out.println(depts);
        return deptService.insertBatch(depts);
    }

}
